package com.cn.wanxi.filter;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.ResultModel;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")//过滤所有的地址（访问后台的地址）
public class MyFilter implements Filter {


    /**
     * servlet的生命周期？
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

//        String path = servletRequest.getServletContext().getRealPath("/");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String path = req.getServletPath();
//        System.out.println(path);
//        判断当前的地址是否是以back开始的即可，就是拦截back开始的地址
        if (!path.startsWith("/back/")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String loginName = (String) req.getSession().getAttribute("username");
        boolean isLogin = loginName == null;
        if (isLogin) {
            //        如果要访问我们后台，需要对地址进行放行
//        } else {
//            resp.sendRedirect("/html/login.html");//这个是在前端页面用jsp的时候才会用
//            return;
            resp.getWriter().println(JSONObject.toJSONString(ResultModel.getModel("未登录，请登录")));
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);

    }


}
